//
//  FileCache.swift
//  j131.tk
//
//  Created by Daniel on 16/3/7.
//  Copyright © 2016年 Daniel. All rights reserved.
//

import Foundation

class FileCache {
    internal static let cacheDirectory = NSHomeDirectory() + "/Library/Caches/files/";
    
    func fileCount() -> Int {
        let fileManager = FileManager.default;
        let enumerator = fileManager.enumerator(atPath: FileCache.cacheDirectory);
        var count = 0;
        while enumerator?.nextObject() != nil {
            count = count + 1;
        }
        return count;
    }
    
    subscript(key: Int) -> String {
        let fileManager = FileManager.default;
        let enumerator = fileManager.enumerator(atPath: FileCache.cacheDirectory)!;
        return enumerator.allObjects[key] as! String;
    }
    
    static func getCachePath(_ key: String) -> String {
        return self.cacheDirectory + key.substring(from: key.characters.index(key.startIndex, offsetBy: 1)).replacingOccurrences(of: "/", with: "_");
    }
    
    static func read(_ key: String) -> URL? {
        if (FileManager.default.fileExists(atPath: self.getCachePath(key))) {
            return URL(fileURLWithPath: self.getCachePath(key));
        } else {
            return nil;
        }
    }
    
    static func write(_ key: String, data: Data) {
        self.remove(key);
        let fileManager = FileManager.default;
        if (!fileManager.fileExists(atPath: self.cacheDirectory)) {
            do {
                try fileManager.createDirectory(atPath: self.cacheDirectory, withIntermediateDirectories: false, attributes: nil);
            } catch {
                
            }
        }
        try? data.write(to: URL(fileURLWithPath: self.getCachePath(key)), options: [.atomic]);
    }
    
    static func remove(_ key: String) {
        let fileManager = FileManager.default;
        if (fileManager.fileExists(atPath: self.getCachePath(key))) {
            do {
                try fileManager.removeItem(atPath: self.getCachePath(key));
            } catch {
                
            }
        }
    }
    
    static func clearAll() -> String {
        let fileManager = FileManager.default;
        let cacheURL = URL(fileURLWithPath: self.cacheDirectory);
        let enumerator = fileManager.enumerator(atPath: self.cacheDirectory);
        var cacheSize:Double = 0;
        while let file = enumerator?.nextObject() as? String {
            do {
                let url = cacheURL.appendingPathComponent(file);
                cacheSize += fileSizeAtPath(url.path);
                try fileManager.removeItem(at: cacheURL.appendingPathComponent(file));
            } catch {
                
            }
        }
        return self.showFileSize(cacheSize);
    }
    
    static func showFileSize (_ size:Double) -> String {
        if (size <= 0.1) {
            return "\(String(format: "%.2f",size * 1024))KB";
        } else {
            return "\(String(format: "%.2f", size))MB";
        }
    }
    
    static func fileSizeAtPath(_ filePath: String) -> Double {
        let manager:FileManager = FileManager.default;
        if (manager.fileExists(atPath: filePath )) {
            do {
                return try ((manager.attributesOfItem(atPath: filePath) as NSDictionary)["NSFileSize"] as! Double)/1024/1024;
            } catch {
                return 0;
            }
        }
        return 0;
    }
}
